package com.example.service;

import com.example.entity.AddressBook;
import com.example.exception.CustomerException;
import com.example.mapper.AddressBookMapper;
import com.example.utils.MapUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@Service
public class AddressBookService {

    @Resource
    AddressBookMapper addressBookMapper;
    @Resource
    MapUtils mapUtils;
    public void add(AddressBook addressBook) {
        addressBookMapper.insert(addressBook);
    }

    public void deleteById(Integer id) {
        addressBookMapper.deleteById(id);
    }

    public void updateById(AddressBook addressBook){
        try {
            if (!selectById(addressBook.getBookId()).getAddress().equals(addressBook.getAddress())) {
                Map<String,String> map = mapUtils.getLonAndLat(addressBook.getAddress());
                addressBook.setLongitude(new BigDecimal(map.get("lng")));
                addressBook.setLatitude(new BigDecimal(map.get("lat")));
            }
            addressBookMapper.updateById(addressBook);
        }catch (Exception e){
            throw new CustomerException("地址簿更新异常");
        }
    }

    public List<AddressBook> selectAll() {
        return addressBookMapper.selectAll();
    }

    public AddressBook selectById(Integer id) {
        return addressBookMapper.selectById(id);
    }

    public PageInfo<AddressBook> selectPage(Integer pageNum, Integer pageSize) {
        //开启分页查询
        PageHelper.startPage(pageNum, pageSize);
        List<AddressBook> list = addressBookMapper.selectAll();
        return PageInfo.of(list);
    }
}
